<template>
  <div class="InfoBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本资料</span>
      </div>
      <el-form :rules="rules" ref="ruleForm" :model="info" class="formbox" label-width="80px">
        <el-form-item label="账户名">
          <el-input v-model="info.account" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="info.username"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
          <el-button type="info" @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { userApi } from '../../apis/user'
const user = userApi()
export default {
  name: 'BasicInfo',
  data () {
    return {
      info: {
        account: '',
        username: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    resetStore () {
      user.getUserInfoById().then(res => {
        this.setUsername(res.data[0].username)
        this.setUserAvatar(res.data[0].avatarurl)
      })
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          user.changeUserInfo(this.info).then(res => {
            if (res.code === 400) {
              this.$message({
                message: '修改失败',
                type: 'error'
              })
            } else {
              this.$message({
                message: '修改成功！',
                type: 'success'
              })
              this.resetForm('ruleForm')
              this.resetStore()
            }
          })
        } else {
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    ...mapActions('user', ['setUsername', 'setUserAvatar'])
  },
  mounted () {
    this.info.account = this.$store.state.user.account
    this.info.username = this.$store.state.user.username
  }
}
</script>

<style lang="less" scoped>
.InfoBox {
  padding: 10px;
  height: 100%;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  height: 100%;
}
.formbox{
  width: 40%;
}
</style>
